package com.wzz.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.xml.soap.SAAJResult;
import java.rmi.server.UID;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author DarkClown
 * @date 2024-08-12 09:45
 * @project_name day0812-month
 * @parem
 **/
@Configuration
public class MyGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String url = request.getPath().toString();

        //登录放过
        if (url.contains("/user/user/login")){
            return chain.filter(exchange);
        }
        //发送验证码
        if (url.contains("/user/user/sendCode")){
            return chain.filter(exchange);
        }
        if (url.contains("/open/open/sendCode")){
            return chain.filter(exchange);
        }
        if (url.contains("/user/user/updatePassword")){
            return chain.filter(exchange);
        }

        List<String> tokens = request.getHeaders().get("token");

        String token = tokens.get(0);
        //查看token
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer uid = body.get("uid", Integer.class);


        //token续期
        Long expire = stringRedisTemplate.getExpire("token" + uid, TimeUnit.MINUTES);

        if (expire<30){
            stringRedisTemplate.expire("token" + uid,30,TimeUnit.MINUTES);
        }


        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
